package com.boc.webmodule.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.boc.webmodule.R;
import com.boc.webmodule.R2;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import demo.bocweb.com.sdk.base.BasePresenter;
import demo.bocweb.com.sdk.base.activity.BaseMVPActivity;
import demo.bocweb.com.sdk.util.PhotoPickerHelper;

/**
 * Created by zhelun on 2018/2/6.
 */

public abstract class BaseWebActivity extends BaseMVPActivity {
    @BindView(R2.id.tv_title)
    TextView tvTitle;
    @BindView(R2.id.tv_menu)
    TextView tvMenu;
    @BindView(R2.id.iv_menu)
    ImageView ivMenu;
    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.web)
    WebView web;
    @BindView(R2.id.progressBar)
    ProgressBar bar;
    private ValueCallback<Uri[]> uploadMessage;
    private ValueCallback<Uri> uploadFile;
    public static final int REQUEST_CODE = 1000;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_webview;
    }

    @Override
    protected void initData() {
        super.initData();
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
        initWebView();
        loadUrl();

    }

    protected abstract void loadUrl();

    private void initWebView() {
        WebSettings webSetting = web.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setBlockNetworkImage(false);
        webSetting.setGeolocationEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            web.getSettings().setMixedContentMode(
                    android.webkit.WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
        web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    bar.setVisibility(View.GONE);
                } else {
                    if (View.INVISIBLE == bar.getVisibility()) {
                        bar.setVisibility(View.VISIBLE);
                    }
                    bar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }


            @Override
            public void openFileChooser(ValueCallback<Uri> valueCallback, String s, String s1) {
                super.openFileChooser(valueCallback, s, s1);
                uploadFile = valueCallback;
                PhotoPickerHelper.selectSinglePhoto(BaseWebActivity.this, REQUEST_CODE, false);
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
                uploadMessage = valueCallback;
                selectMultiPhoto();

                return true;
            }
        });
        web.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                // handler.cancel();// Android默认的处理方式
                handler.proceed();// 接受所有网站的证书
                // handleMessage(Message msg);// 进行其他处理
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                overrideUrl(view, url);
                return true;
            }

        });
    }

    //PhotoPickerHelper.selectMultiPhoto(BaseWebActivity.this, 1000, 9);
    protected abstract void selectMultiPhoto();


    public abstract void overrideUrl(WebView view, String url);

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == REQUEST_CODE) {
                    if (null != uploadFile) {
                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                        // 例如 LocalMedia 里面返回三种path
                        // 1.media.getPath(); 为原图path
                        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                        // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                        Uri result;
                        if (selectList.get(0).isCompressed()) {
                            result = Uri.fromFile(new File(selectList.get(0).getCompressPath()));
                        } else {
                            result = Uri.fromFile(new File(selectList.get(0).getPath()));
                        }

                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (uploadMessage != null) {
                        List<LocalMedia> photos = PictureSelector.obtainMultipleResult(data);
                        Uri[] uris = new Uri[photos.size()];
                        for (int i = 0; i < photos.size(); i++) {
                            Uri result;
                            if (photos.get(i).isCompressed()) {
                                result = Uri.fromFile(new File(photos.get(i).getCompressPath()));
                            } else {
                                result = Uri.fromFile(new File(photos.get(i).getPath()));
                            }
                            uris[i] = result;
                        }
                        uploadMessage.onReceiveValue(uris);
                        uploadMessage = null;
                    }
                }

            }
        } else {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }
            if (null != uploadMessage) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            }

        }
    }
}
